import _ from 'lodash-es'
import { CacheApi } from '../types'

interface Area {
  id: number
  parentid: number
  areacode: string
  areaname: string
  latitude: string
  longitude: string
  level: string
  childrens: Area[]
  // 追加键值
  label: string
  value: string
  key: string
}

// 树遍历追加键值
function buildAreaTree(tree: Area[] = []) {
  tree.forEach(el => {
    el.label = el.areaname
    el.value = el.areaname
    el.key = String(el.id)
    if (el.childrens && el.childrens.length) {
      buildAreaTree(el.childrens)
    }
  })

  return tree
}

// 修改了树结构，去除了四个直辖市的中间层节点
function handleAreaTree(tree: Area[] = []) {
  const arr = ['北京市', '上海市', '天津市', '重庆市']
  tree.forEach(el => {
    if (arr.includes(el.areaname)) {
      let elChildrens: Area[] = []
      el.childrens.forEach(elC => {
        elC.childrens.forEach(elCC => (elCC.parentid = el.id))
        elChildrens = [...elChildrens, ...elC.childrens]
      })
      el.childrens = elChildrens
    }
  })
  return buildAreaTree(tree)
}

export const cache_areaTree: CacheApi = {
  name: 'cache_areaTree',
  url: '/sys/area/tree',
  method: 'get',
  isInit: true,
  responseFormate: (res: any) => {
    // 此处会改变数据原始结构，故需要深度克隆
    return handleAreaTree(_.cloneDeep(res))
  }
}
